<template>
  <div class="register-page">
    <div class="register-dialog">
      <div class="register-dialog-content">
        <div class="logo-section">
          <IconDeepseekText class="logo-svg" />
        </div>
        <div class="register-panel">
          <div class="form-content">
            <div class="page-notice-top">
              {{ pageNotice }}
            </div>

            <div class="input-group">
              <div class="input-wrapper">
                <div class="input-prefix">
                  <IconPhone class="icon-form icon-phone" />
                </div>
                <span class="country-code-label">+86</span>
                <input
                  type="tel"
                  placeholder="请输入手机号"
                  class="form-input phone-number-input"
                  v-model="phoneNumber"
                />
              </div>
              <div class="form-message">{{ phoneNumberError }}</div>
            </div>

            <div class="input-group">
              <div class="input-wrapper">
                <div class="input-prefix">
                  <IconLock class="icon-form" />
                </div>
                <input
                  :type="passwordFieldType"
                  placeholder="请输入密码"
                  class="form-input"
                  v-model="password"
                />
                <div class="password-toggle" tabindex="0" @click="togglePasswordVisibility" @keyup.enter="togglePasswordVisibility" @keyup.space="togglePasswordVisibility">
                  <IconEye class="icon-form" />
                </div>
              </div>
              <div class="form-message">{{ passwordError }}</div>
            </div>

            <div class="input-group">
              <div class="input-wrapper">
                <div class="input-prefix">
                  <IconLock class="icon-form" />
                </div>
                <input
                  :type="confirmPasswordFieldType"
                  placeholder="请再次输入密码"
                  class="form-input"
                  v-model="confirmPassword"
                />
                <div class="password-toggle" tabindex="0" @click="toggleConfirmPasswordVisibility" @keyup.enter="toggleConfirmPasswordVisibility" @keyup.space="toggleConfirmPasswordVisibility">
                  <IconEye class="icon-form" />
                </div>
              </div>
              <div class="form-message">{{ confirmPasswordError }}</div>
            </div>

            <div class="input-group">
              <div class="code-input-container">
                <div class="input-wrapper">
                  <div class="input-prefix">
                    <IconVerificationHash class="icon-form icon-code-hash" />
                  </div>
                  <input
                    maxlength="6"
                    type="tel"
                    placeholder="请输入验证码"
                    class="form-input verification-code-input"
                    v-model="verificationCode"
                  />
                </div>
                <button type="button" class="button button-outline send-code-button" @click="sendVerificationCode" :disabled="isSendingCode">
                  {{ sendCodeButtonText }}
                </button>
              </div>
              <div class="form-message">{{ verificationCodeError }}</div>
            </div>

            <div class="agreement-section">
              <p class="agreement-text">
                注册即代表已阅读并同意我们的
                <a href="https://cdn.deepseek.com/policies/zh-CN/deepseek-terms-of-use.html" target="_blank" rel="noopener noreferrer" class="link agreement-link">用户协议</a>
                与
                <a href="https://cdn.deepseek.com/policies/zh-CN/deepseek-privacy-policy.html" target="_blank" rel="noopener noreferrer" class="link agreement-link">隐私政策</a>
              </p>
            </div>

            <button type="button" class="button button-primary action-button-fullwidth" @click="handleRegister">注册</button>

            <div class="navigation-links">
               <div role="button" tabindex="0" class="action-link" @click="goToLogin">返回登录</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useUserStore } from '@/store/user';
import IconDeepseekText from '@/components/icons/IconDeepseekText.vue';
import IconPhone from '@/components/icons/IconPhone.vue';
import IconVerificationHash from '@/components/icons/IconVerificationHash.vue'; // The new icon
import IconLock from '@/components/icons/IconLock.vue';
import IconEye from '@/components/icons/IconEye.vue';
import { validatePhoneNumber } from '@/util';
import { useRouter } from 'vue-router';
import { onUnmounted } from 'vue';
import {
  sendLoginOtp,
  registerUser,
  currentUser,
  isLoading,
  errorMessage
} from '@/types/api';

const router = useRouter();

// Reactive State
const pageNotice = ref('你所在地区仅支持手机号注册，只需一个 DeepSeek 账号，即可访问 DeepSeek 的所有服务。');
const phoneNumber = ref('');
const password = ref('');
const showPassword = ref(false);
const confirmPassword = ref('');
const showConfirmPassword = ref(false);
const verificationCode = ref('');

// Error message states
const phoneNumberError = ref('');
const passwordError = ref('');
const confirmPasswordError = ref('');
const verificationCodeError = ref('');

// Send code button state
const isSendingCode = ref(false);
const sendCodeButtonText = ref('发送验证码');
let countdownTimer = null;


// Computed properties for password field types
const passwordFieldType = computed(() => (showPassword.value ? 'text' : 'password'));
const confirmPasswordFieldType = computed(() => (showConfirmPassword.value ? 'text' : 'password'));

// Methods
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

const validatePhoneNumberInput = () => {
  if (!phoneNumber.value) {
    phoneNumberError.value = '请输入手机号';
    return false;
  }

  if (!validatePhoneNumber(phoneNumber.value)) {
    phoneNumberError.value = '请输入正确的手机号格式';
    return false;
  }

  phoneNumberError.value = '';
  return true;
};

const sendVerificationCode = async () => {
  if (!validatePhoneNumberInput()) return;
  if (isSendingCode.value) return;

  isSendingCode.value = true;
  sendCodeButtonText.value = '发送中...';
  
  try {
    const success = await sendLoginOtp({ phone_number: phoneNumber.value });
    if (success) {
      let countdown = 60;
      sendCodeButtonText.value = `${countdown}s后重发`;
      countdownTimer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
          clearInterval(countdownTimer);
          sendCodeButtonText.value = '发送验证码';
          isSendingCode.value = false;
        } else {
          sendCodeButtonText.value = `${countdown}s后重发`;
        }
      }, 1000);
    }
  } catch (error) {
    console.error('Failed to send verification code:', error);
    verificationCodeError.value = errorMessage.value || '验证码发送失败，请稍后重试';
    sendCodeButtonText.value = '发送验证码';
    isSendingCode.value = false;
  }
};

const validateForm = () => {
  let isValid = true;
  if (!validatePhoneNumberInput()) isValid = false;

  if (!password.value) {
    passwordError.value = '请输入密码';
    isValid = false;
  } else if (password.value.length < 6) { // Example: min length
    passwordError.value = '密码长度至少为6位';
    isValid = false;
  } else {
    passwordError.value = '';
  }

  if (!confirmPassword.value) {
    confirmPasswordError.value = '请再次输入密码';
    isValid = false;
  } else if (password.value !== confirmPassword.value) {
    confirmPasswordError.value = '两次输入的密码不一致';
    isValid = false;
  } else {
    confirmPasswordError.value = '';
  }

  if (!verificationCode.value) {
    verificationCodeError.value = '请输入验证码';
    isValid = false;
  } else if (verificationCode.value.length !== 6) { // Example: exact length
    verificationCodeError.value = '验证码必须为6位数字';
    isValid = false;
  } else {
    verificationCodeError.value = '';
  }
  return isValid;
};

const handleRegister = async () => {
  if (!validateForm()) {
    return;
  }

  try {
    const user = await registerUser({
      phone_number: phoneNumber.value,
      password: password.value
    });
    if (user) {
      const userStore = useUserStore();
      userStore.setUser(user);
      router.push('/login');
    }
  } catch (error) {
    verificationCodeError.value = errorMessage.value || '注册失败，请稍后再试';
  }
};

const goToLogin = () => {
  console.log('Navigating to login page');
  router.push('/login');
};

// Clear countdown on component unmount

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

</script>

<style lang="scss" scoped>
// Import or define SCSS variables and base styles similar to LoginPage.vue
// For example:
$primary-color: #4D6BFE;
$text-primary: #262626;
$text-secondary: #404040;
$text-muted: #a3a3a3;
$border-color: #e5e5e5;
$white: #fff;
$error-color: #D32F2F; // Standard Material Design error color
$font-family-base: 'DeepSeek-CJK-patch', Inter, system-ui;

// --- START --- Replicate styles from LoginPage.vue or ensure they are globally available ---
// Base Page Setup
.register-page { // Changed from login-page
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding-top: 4px;
  font-family: $font-family-base; // Make sure $font-family-base is defined
  background-color: $white; // Make sure $white is defined
  font-size: 14px;
  line-height: 1.5;

  @media (max-width: 768px) {
    justify-content: flex-start;
    padding: 20px;
  }
}

.register-dialog-content { // Changed from login-dialog-content
  padding-top: 48px;

  @media (max-width: 768px) {
    padding-top: 0;
    width: 100%;
  }
}

.logo-section {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  .logo-svg {
    height: 44px;
    width: auto;
  }

  @media (max-width: 768px) {
    margin-bottom: 30px;
    .logo-svg {
      height: 36px;
    }
  }
}

.register-panel { // Changed from login-panel
  border-radius: 16px;
  box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 4px 0 rgba(0, 0, 0, 0.02), 0 12px 36px 0 rgba(0, 0, 0, 0.06);
  padding: 12px;
  min-height: 420px; // Adjust as needed for more fields
  background-color: $white;

  @media (max-width: 768px) {
    box-shadow: none;
    padding: 0;
    min-height: auto;
    border-radius: 0;
    width: 100%;
  }
}

.form-content {
  display: flex;
  flex-direction: column;
  padding: 24px 24px 16px;
  width: 408px;
  max-width: 100%;

  @media (max-width: 768px) {
    width: auto;
    padding: 20px;
  }
}

.page-notice-top { // Renamed from login-notice for specificity
  color: $text-muted; // Use defined SCSS variable
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 16px; // Increased margin for better separation
  padding: 0 2px;
  text-align: left; // As per original HTML structure
}

// Input Fields (largely same as login page)
.input-group {
  margin-bottom: 4px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: transparent;
  border-radius: 10px;
  height: 44px;
  padding: 0 10px;
  position: relative;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  border: 1px solid $border-color;

  &:focus-within {
    border-color: $primary-color;
    box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
  }
}

.input-prefix {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  color: $text-muted;

  .icon-form { // Generic class for icons in forms
    width: 18px;
    height: 18px;
    fill: currentColor; // Ensure SVG icons inherit color
  }
  /* Specific icon styles if needed */
}

.country-code-label {
  color: $text-primary;
  line-height: 44px;
  margin-right: 8px;
  white-space: nowrap;
}

.form-input {
  flex-grow: 1;
  font-family: $font-family-base;
  font-size: 14px;
  background-color: transparent;
  caret-color: $primary-color;
  color: $text-secondary;
  border: none;
  outline: none;
  padding: 0;
  height: 100%;

  &::placeholder {
    color: $text-muted;
    opacity: 1;
  }
}

.code-input-container {
  display: flex;
  align-items: center;

  .input-wrapper {
    flex-grow: 1;
    margin-right: 12px;
  }
}

.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  color: $text-muted; // Match placeholder color for muted feel
  width: 18px; // Ensure clickable area
  height: 18px;

  .icon-form { // Ensure eye icon is also 18x18
      width: 18px;
      height: 18px;
  }
  &:hover {
    color: $text-secondary; // Darken on hover
  }
}

.form-message {
  font-size: 12px;
  line-height: 1.4;
  min-height: 21px;
  padding: 2px 2px 6px;
  color: $error-color; // Use a defined error color variable
  text-align: left;
}

// Buttons (largely same as login page)
.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  font-size: 14px;
  height: 44px;
  padding: 0 14px;
  text-decoration: none;
  white-space: nowrap;
  transition: background-color 0.2s ease, border-color 0.2s ease, opacity 0.2s ease;
  user-select: none;
  cursor: pointer;
  border: 1px solid transparent;
  outline: none;

  &:active {
    opacity: 0.85;
  }
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background-color: lighten($text-muted, 25%); // Example disabled style for outline button
    border-color: lighten($text-muted, 15%);
    color: $text-muted;
  }
}

.button-outline {
  background-color: $white;
  border-color: $border-color;
  color: $text-primary;

  &:hover:not(:disabled) {
    background-color: lighten($border-color, 5%);
    border-color: darken($border-color, 8%);
  }
   &:disabled { // Specific disabled style for outline if different
    background-color: $white;
    border-color: lighten($border-color, 5%);
    color: $text-muted;
  }
}

.button-primary {
  background-color: $primary-color;
  color: $white;
  font-weight: 500;

  &:hover:not(:disabled) {
    background-color: darken($primary-color, 8%);
  }
   &:disabled {
    background-color: lighten($primary-color, 20%);
    border-color: lighten($primary-color, 20%);
   }
}

.send-code-button {
  // Inherits .button and .button-outline
  // Can add specific width or flex-shrink if needed
  flex-shrink: 0; // Prevent shrinking if input field is long
}

.action-button-fullwidth { // Renamed from login-button
  width: 100%;
  margin-top: 20px;
}

// Agreement Section (largely same as login page)
.agreement-section {
  margin-top: 16px;
  margin-bottom: 8px;
  .agreement-text {
    color: $text-muted;
    font-size: 12px;
    line-height: 1.5;
    margin:0;
    text-align: left; // Align with general form text

    .link.agreement-link {
      color: $text-primary; // Consistent with original registration HTML link style
      text-decoration: none; // Original has no underline, add if desired
      // padding: 2px 3px; // Keep if you want a slight "button" feel on hover
      // border-radius: 4px;
      transition: color 0.2s ease;

      &:hover {
        color: $primary-color;
        text-decoration: underline; // Add underline on hover for clarity
      }
       &:focus-visible {
        outline: 2px solid $primary-color;
        outline-offset: 2px;
      }
    }
  }
}

// Navigation Links (for "Back to Login")
.navigation-links {
  display: flex;
  justify-content: center; // Center the link
  margin-top: 20px; // Spacing from the register button
  font-size: 14px;  // Consistent font size
  font-weight: 500;

  .action-link { // Similar to .action-button in login, but centered
    color: $primary-color;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 8px;
    transition: background-color 0.2s ease, color 0.2s ease;

    &:hover {
      color: darken($primary-color, 10%);
      // background-color: rgba($primary-color, 0.1); // Optional subtle background
      text-decoration: underline;
    }
    &:focus-visible {
      outline: 2px solid $primary-color;
      outline-offset: 2px;
    }
  }
}
// --- END --- Replicated/Adapted Styles ---
</style>